#lang rosetta-racket


(define blacklist-distros (list ".svn" "compiled"))

(define (find-distros)
  (filter
   (λ (p) (and (directory-exists? p) (not (member (path->string (file-name-from-path p)) blacklist-distros))))
   (map
    (λ (p) (path->complete-path p (rosetta-distros-path)))
    (directory-list (rosetta-distros-path)))))

(define (write-require path)
  (write-string (format "(require \"~A/src/main.rkt\")" (file-name-from-path path))))

(define (write-provide path)
  (write-string (format "(provide (all-from-out \"~A/src/main.rkt\"))" (file-name-from-path path))))

(define (write-require-buffer path)
  (displayln "#lang racket")
  (newline)
  (newline)
  (write-require path)
  (newline)
  (newline)
  (write-provide path))

(define (require-file-path path)
  (format "~A.rkt" (path->complete-path (file-name-from-path path) (rosetta-distros-path))))

(define (write-require-file path)
  (with-output-to-file (require-file-path path)
    (λ () (write-require-buffer path))
    #:mode 'text
    #:exists 'truncate/replace))

(define (write-require-distros)
  (for-each write-require-file (find-distros)))

(define (write-main-require-distro)
  (with-output-to-file (build-path (rosetta-distros-path) "main.rkt")
    (λ ()
      (displayln "#lang racket")
      (newline)
      (newline)
      (for-each
       (λ (d) (displayln (format "(require \"~A.rkt\")" (file-name-from-path d))))
       (find-distros))
      (newline)
      (for-each
       (λ (d) (displayln (format "(provide (all-from-out \"~A.rkt\"))" (file-name-from-path d))))
       (find-distros)))
    #:mode 'text
    #:exists 'truncate/replace))

(define (write-requires)
  (write-require-distros)
  (write-main-require-distro))